package com.sixmac.service.impl;

import com.sixmac.controller.common.CommonController;
import com.sixmac.core.Constant;
import com.sixmac.dao.AppUserDao;
import com.sixmac.dao.SysUserDao;
import com.sixmac.entity.AppUser;
import com.sixmac.entity.SysUser;
import com.sixmac.service.AccountService;
import com.sixmac.service.AppUserService;
import com.sixmac.service.OperaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Created by Administrator on 2016/3/4 0004 下午 2:55.
 */
@Service
public class AppUserServiceImpl implements AppUserService {

    @Autowired
    private AppUserDao appUserDao;

    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private OperaService operaService;

    @Autowired
    private AccountService accountService;

    @Override
    public List<AppUser> findAll() {
        return appUserDao.findAll();
    }

    @Override
    public Page<AppUser> find(int pageNum, int pageSize) {
        return appUserDao.findAll(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Page<AppUser> find(int pageNum) {
        return find(pageNum, Constant.PAGE_DEF_SIZE);
    }

    @Override
    public AppUser getById(int id) {
        AppUser appUser = appUserDao.findOne(id);
        return appUser;
    }

    @Override
    public AppUser deleteById(int id) {
        AppUser appUser = getById(id);
        appUser.setStatus(Constant.STATUS_NO);
        appUserDao.save(appUser);
        return appUser;
    }

    @Override
    @Transactional
    public void deleteById(HttpServletRequest request, Integer id) {
        AppUser appUser = getById(id);
        appUser.setStatus(Constant.STATUS_NO);
        appUserDao.save(appUser);

        operaService.addOperaInfo(request, "删除用户 " + appUser.getMobile());
    }

    @Override
    public AppUser create(AppUser appUser) {
        return appUserDao.save(appUser);
    }

    @Override
    public AppUser update(AppUser appUser) {
        return appUserDao.save(appUser);
    }

    @Override
    @Transactional
    public void deleteAll(int[] ids) {
        for (int id : ids) {
            deleteById(id);
        }
    }

    @Override
    public SysUser sysUserLogin(HttpSession session, String username, String password) {
        SysUser sysUser = appUserDao.sysUserLogin(username, password);
        if (null != sysUser) {
            // 更新最后一次登录时间
            sysUser.setLoginTime(new Date());
            sysUserDao.save(sysUser);

            putSession(session, sysUser.getId(), sysUser.getAccount());
            return sysUser;
        }

        return null;
    }

    @Override
    public void logOut(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        session.removeAttribute(Constant.CURRENT_USER_ID);
        session.removeAttribute(Constant.CURRENT_USER_NAME);
    }

    @Override
    public AppUser iLogin(String mobile, String password) {
        return appUserDao.iLogin(mobile, password);
    }

    @Override
    public AppUser iLogin(String mobile) {
        return appUserDao.iLogin(mobile);
    }

    @Override
    public AppUser iFindOneByMobile(String mobile) {
        AppUser appUser = appUserDao.iFindOneByMobile(mobile);
        return appUser;
    }

    @Override
    public Page<AppUser> page(final String mobile, final Integer status, Integer pageNum, Integer pageSize) {
        Page<AppUser> page = appUserDao.findAll(new Specification<AppUser>() {
            @Override
            public Predicate toPredicate(Root<AppUser> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate result = null;
                List<Predicate> predicateList = new ArrayList<Predicate>();

                if (mobile != null) {
                    Predicate pre = cb.like(root.get("mobile").as(String.class), "%" + mobile + "%");
                    predicateList.add(pre);
                }

                if (status != null) {
                    Predicate pre = cb.equal(root.get("status").as(Integer.class), status);
                    predicateList.add(pre);
                }

                if (predicateList.size() > 0) {
                    result = cb.and(predicateList.toArray(new Predicate[]{}));
                }

                if (result != null) {
                    query.where(result);
                }
                return query.getGroupRestriction();
            }

        }, new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));

        return page;
    }

    @Override
    public List<AppUser> findListNew() {
        return appUserDao.findListNew(CommonController.getOldDate());
    }

    @Override
    public void deleteAll(HttpServletRequest request, int[] ids) {
        for (int id : ids) {
            deleteById(request, id);
        }
    }

    @Override
    public AppUser update(HttpServletRequest request, Integer id, Integer status) {
        AppUser appUser = appUserDao.findOne(id);
        appUser.setStatus(status);

        operaService.addOperaInfo(request, (status == 0 ? "启用" : "禁用") + "APP用户 " + appUser.getMobile());

        return appUserDao.save(appUser);
    }

    @Override
    public void updateAll(HttpServletRequest request, int[] ids, Integer status) {
        for (int id : ids) {
            update(request, id, status);
        }
    }

    @Override
    public List<AppUser> findList(String mobile) {
        mobile = "%" + mobile + "%";
        return appUserDao.findList(mobile);
    }

    @Override
    public List<Map<String, Object>> pageToExcel(HttpServletRequest request, Map<String, Object> params) {
        List<AppUser> appUserList = appUserDao.findAll();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = null;

        for (AppUser appUser : appUserList) {
            map = new HashMap<String, Object>();
            map.put("mobile", appUser.getMobile());
            map.put("createTime", appUser.getCreateTime().toString().substring(0, appUser.getCreateTime().toString().length() - 2));
            map.put("score", appUser.getScore());
            map.put("count", accountService.findListById(appUser.getId(), Constant.ACCOUNT_STATUS_App).size());
            map.put("status", appUser.getStatus() == Constant.STATUS_YES ? "启用" : "禁用");

            list.add(map);
        }

        operaService.addOperaInfo(request, "导出APP用户数据");

        return list;
    }

    // 将登录人的信息放入session中
    private void putSession(HttpSession session, Integer id, String name) {
        session.setAttribute(Constant.CURRENT_USER_ID, id);
        session.setAttribute(Constant.CURRENT_USER_NAME, name);
    }
}